"""
通用依赖项模块
提供可复用的依赖注入函数，如获取当前用户ID
"""
from typing import Optional
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.core.security import decode_access_token
from app.utils.exceptions import UnauthorizedException

# OAuth2 密码承载方案，用于从请求头中提取 Bearer Token
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/auth/login")


async def get_current_user_id(
    token: str = Depends(oauth2_scheme),
    db: Session = Depends(get_db)
) -> Optional[int]:
    """
    从 JWT 令牌中提取当前用户ID的依赖函数
    用于需要认证的接口
    
    Args:
        token: 从请求头中提取的 JWT 令牌
        db: 数据库会话
        
    Returns:
        Optional[int]: 用户ID，如果令牌无效则抛出异常
        
    Raises:
        UnauthorizedException: 令牌无效或过期时抛出
    """
    payload = decode_access_token(token)
    if payload is None:
        raise UnauthorizedException("无效的访问令牌")
    user_id: Optional[int] = payload.get("sub")  # JWT 标准中用户ID存储在 "sub" 字段
    if user_id is None:
        raise UnauthorizedException("无效的访问令牌")
    return user_id


